<template>
    <div class="login">
    <div class="title">欢迎登录</div>
      <van-form>
          <van-field
            v-model="username"
            name="用户名"
            label="用户名"
            placeholder="请输入用户名"
            size="large"
            :rules="[{ required: true, message: '用户名不能为空' }]"
          />
          <van-field
            v-model="password"
            type="password"
            name="validator"
            label="密码"
            placeholder="请输入密码"
            size="large"
            :rules="[{ required: true, message: '请填写密码' },{validator: validatePassword,message: '密码长度至少为6位'}]"
          />
        <div style="margin-top: 16px;">
          <van-button round block type="primary" @click="onSubmit">登录</van-button>
        </div>
        <div class="footer">
        <span>没有账号,</span>
        <span class="register" @click="goRegister">去注册</span>
        </div>
      </van-form>
    </div>
  </template>
  
  <script>
  import { ref, getCurrentInstance, onMounted } from 'vue'
  import router from '../router/index';
  export default {
    setup (props, cxt) {
      const { proxy } = getCurrentInstance()
      const username = ref('');
      const password = ref('');
      let loginInfo;
      const validatePassword = (val) => /\d{6}/.test(val);
  
      const onSubmit = async () => {
        let data = {username: username.value,password: password.value}
        loginInfo = await proxy.$axios.post('/login', data)
        // console.log(loginInfo);
  
        if (username.value != loginInfo.username || password.value != loginInfo.password + '') {
          proxy.$toast.fail('用户名或密码错误...');
        } else {
          localStorage.setItem('isLogin', JSON.stringify(true))
          localStorage.setItem('user', username.value)
          proxy.$toast.success('登录成功')
          router.push('/home')
        }
      }
  
      const goRegister = () => {
        router.push('/register')
      }
  
      onMounted(() => {
      });
  
  
      return {
        username,
        password,
        validatePassword,
        onSubmit,
        goRegister
      };
    },
  }
  </script>
  
  <style scoped>
  .login{

    background-color: #eee;
    height: 100%;
  }
  .title{
    font-size: 1.75rem;
  }
  .van-form{
    height: 18.75rem;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  .van-cell--large{
    margin: 0.625rem 0;
    border-radius: 8px;
  }
  .footer{
      color: #ccc;
      text-align: center;
      font-size: 0.875rem;
      padding: 0.625rem 0;
  }
  .register{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #aaa;
    font-weight: bold;
  }
  </style>